/**
 * 				ClientMain.java
 *				------------
 *		
 *   Author:	bin04017@gmail.com
 *	 Created:	13.12.2006
 *	 Project:	MP3-Sync (Mochito)
 *	 Package:	testMains
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */
package mochito.clientClasses.clientRMI;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.Set;

import mochito.dataClasses.musicItem.MusicItem;
import mochito.serverClasses.ServerInterface;

/**
 * @author  bin04017
 */
public class ClientRMI {
	
	private ServerInterface server = null;
	
	private String host = null;
	
	public ClientRMI(String host) throws Exception{
		this.host = host;
		this.getCurrentConnect();
	}
	/**
	 * @return  the host
	 */
	public String getHost() {
		return host;
	}

	private ServerInterface getCurrentConnect() throws Exception{
		if(server == null){
			try{
				server = (ServerInterface) Naming.lookup("rmi://" + host + "/MP3");
			}catch(Exception e){
				throw new Exception("Connection refused. Maybe the server is not running");
			}
		} 
		return server;
	}
	public Set<String> getMusicItems() throws RemoteException{
		return server.getMusicItems();
	}
	private File getFile(String name, String dir) throws IOException{
		RandomAccessFile rmp3 = null;
		File mp3 = null;
		try {
			byte[] bArray = server.retrieveFile(name);
			rmp3 = new RandomAccessFile(dir+"/"+name+".mp3","rw");
			rmp3.write(bArray);
			rmp3.close();
			mp3 = new File(dir+"/"+name+".mp3");
		} catch (Exception e){
			
		}
		return mp3;
	}
	public MusicItem getMusicItem(String name, String dir) throws IOException{
		String date = server.getMusicItemStartDate(name);
		String time = server.getMusicItemStartTime(name);
		File mp3 = this.getFile(name, dir);
		MusicItem item = new MusicItem(name, mp3);
		item.setStartTime(time);
		item.setStartDate(date);
		return item;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
